//
//  OrderDetailViewController.m
//  OrderSeat
//
//  Created by haiming on 13-10-10.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "OrderDetailViewController.h"
#import "MyOrderViewController.h"
#import "ShopHomeViewController.h"
#import "OrderSeatsViewController.h"
#import "OrderDishesViewController.h"
#import "MapViewController.h"
#import "HomeViewController.h"
#import "OrderDetailCell.h"

#define ORDER_SHOP @"预定餐厅"
#define SHOP_ADDR @"餐厅地址"
#define SHOP_TEL @"餐厅电话"
#define DISH_TEXT @"菜       品"
#define DISH_M_CONTENT @"%@ %@道菜/￥%@"
#define DISH_S_CONTENT @"%@道菜/￥%@"
#define PACK_M_CONTENT @"%@ %@ %@份/￥%@"
#define PACK_S_CONTENT @"%@ %@份/￥%@"
#define ORDER_TIME @"预定时间"
#define DINNER_TIME @"就餐时间"
#define DINNER_COUNT @"就餐人数"
#define SEAT_TEXT @"座       位"
#define ORDER_TEL @"预留电话"
#define REMARK_TEXT @"备       注"
#define TITLE @"title"
#define CONTENT @"content"

@interface OrderDetailViewController()

@property (copy,   nonatomic) NSString *shopId;
@property (copy,   nonatomic) NSString *shopName;
@property (copy,   nonatomic) NSString *tel;
@property (copy,   nonatomic) NSString *seatName;
@property (copy,   nonatomic) NSString *seatType;
@property (copy,   nonatomic) NSString *dinnerTime;
@property (assign, nonatomic) int orderseatType;

@property (strong, nonatomic) NSMutableDictionary *shopInfo;

@end

@implementation OrderDetailViewController

- (id)initWithOrderId:(NSString*)orderId andType:(OrderType)orderType
{
    self = [super initWithNibClass:[OrderDetailViewController class]];
    if (self) {
        self.orderId = orderId;
        self.orderType = orderType;
        self.shopInfo = [NSMutableDictionary dictionary];
        _dataSource = [[OrderDetailDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    [_dataSource fetchOrderInfo];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"我的订单"];
    
    _cancelOrderBtn.hidden = !(_orderType == NewOrder);
    _theScrollview.hidden = YES;
    
    _headTable.delegate = _detailTable.delegate = _dataSource;
    _headTable.dataSource = _detailTable.dataSource = _dataSource;
}

- (void)leftButtonClick:(id)sender
{
    [self pushOrPopViewController:[MyOrderViewController class]];
}

- (void)rightButtonClick:(id)sender
{
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    if([MFMessageComposeViewController canSendText])
    {
        NSString *text = [NSString stringWithFormat:@"我在 “%@“ 餐厅预定了%@ %@“%@”餐位，请您前来就餐！",_shopName,_dinnerTime,_seatType,_seatName];
        controller.messageComposeDelegate = self;
        controller.body = text;
        [self presentViewController:controller animated:YES completion:^{}];
    }
}

// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent");
    else
        NSLog(@"Message failed");
    
    [self dismissViewControllerAnimated:YES completion:^{}];
}

- (void)rowSelect:(NSDictionary *)dic
{
    NSString *dishId = [dic objectForKey:@"id"];
    NSString *title = [dic objectForKey:TITLE];
    
    if ([title isEqualToString:ORDER_SHOP]) {
        ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:_shopId];
        shopHomeVC.parentViewController = self;
        [AppDelegate changeToShopTabBar:shopHomeVC];
        
        [self pushViewController:shopHomeVC];
    }
    
    if ([title isEqualToString:SHOP_ADDR]) {
        MapViewController *mapView = [[MapViewController alloc] initWithShopInfo:_shopInfo];
        [self pushViewController:mapView];
    }
    
    if ([title isEqualToString:SHOP_TEL]) {
        [self callPhone];
    }
    
    if ([title isEqualToString:SEAT_TEXT]) {
        OrderSeatsViewController *orderSeatsVC = [[OrderSeatsViewController alloc] initWithOrderId:_orderId andSeatType:_orderseatType];
        [self pushViewController:orderSeatsVC];
    }
    
    if ([title isEqualToString:DISH_TEXT]) {
        OrderDishesViewController *dishesVC = [[OrderDishesViewController alloc] initWithDishId:dishId];
        dishesVC.orderType = _orderType;
        [self pushViewController:dishesVC];
    }
}

- (void)callPhone
{
    NSString *tel = _tel;
    tel = [NSString stringWithFormat:@"tel:%@", tel];
    
    UIWebView *callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:tel];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    
    [self.view addSubview:callWebview];
}

- (IBAction)cancelOrderAction:(id)sender
{
    [_dataSource cancelOrder];
}

- (void)setFormValues:(NSDictionary*)dictionary
{
    NSString *eattime = [dictionary objectForKey:@"eattime"];
    NSString *zaowan  = [dictionary objectForKey:@"zaowan"];
    NSString *dinnerTime = [eattime stringByAppendingFormat:@" %@", zaowan];
    NSString *orderTime = [dictionary objectForKey:@"add_time"];
    NSString *seatType = [dictionary objectForKey:@"zwtype"];
    NSString *seatName = [dictionary objectForKey:@"zwname"];
    NSString *seat = [NSString stringWithFormat:@"%@(%@)",seatType,seatName];
    NSArray *dishs = [dictionary objectForKey:@"dish"];
    
    NSString *state = [dictionary objectForKey:@"zt"];
    NSString *dname = [dictionary objectForKey:@"dname"];
    NSString *address = [dictionary objectForKey:@"dz"];
    NSString *tel = [dictionary objectForKey:@"tel"];
    
    NSString *ordertel = [dictionary objectForKey:@"ordertel"];
    NSString *remark = [dictionary objectForKey:@"beizhu"];
    NSString *dinnerCount = [dictionary objectForKey:@"renshu"];
    remark = [remark isEqual:[NSNull null]] ? @"无" : remark;
    
    NSString *jingdu = [dictionary objectForKey:@"jingdu"];
    NSString *weidu = [dictionary objectForKey:@"weidu"];
    
    NSMutableArray *head = [[NSMutableArray alloc] init];
    NSMutableArray *detail = [[NSMutableArray alloc] init];
    
    [head addObject:[NSDictionary dictionaryWithObjectsAndKeys:ORDER_SHOP,TITLE,dname,CONTENT, nil]];
    [head addObject:[NSDictionary dictionaryWithObjectsAndKeys:SHOP_ADDR,TITLE,address,CONTENT, nil]];
    [head addObject:[NSDictionary dictionaryWithObjectsAndKeys:SHOP_TEL,TITLE,tel,CONTENT, nil]];
    _dataSource.headList = head;
    
    [detail addObject:[NSDictionary dictionaryWithObjectsAndKeys:DINNER_TIME,TITLE,dinnerTime,CONTENT, nil]];
    
    if (seat.length > 0 && ![seat isEqualToString:@"()"]) {
        [detail addObject:[NSDictionary dictionaryWithObjectsAndKeys:SEAT_TEXT,TITLE,seat,CONTENT, nil]];
    }
    
    for (NSDictionary *dish in dishs) {
        NSString *did = [dish objectForKey:@"id"];
        NSString *tname  = [dish objectForKey:@"tname"];
        NSString *zuname = [dish objectForKey:@"zuname"];
        NSString *zongjia = [dish objectForKey:@"zongjia"];
        NSString *fenshu = [dish objectForKey:@"fenshu"];
        NSString *content = @"";
    
        if ((zuname && zuname.length > 0) && !(tname && tname.length > 0)) {
            content = [NSString stringWithFormat:DISH_M_CONTENT,zuname,fenshu,zongjia];
        }else if(!(zuname && zuname.length > 0) && !(tname && tname.length > 0)){
            content = [NSString stringWithFormat:DISH_S_CONTENT,fenshu,zongjia];
        }
        
        if ((zuname && zuname.length > 0) && (tname && tname.length > 0)) {
            content = [NSString stringWithFormat:PACK_M_CONTENT,zuname,tname,fenshu,zongjia];
        }else if(!(zuname && zuname.length > 0) && (tname && tname.length > 0)){
            content = [NSString stringWithFormat:PACK_S_CONTENT,tname,fenshu,zongjia];
        }
        
        [detail addObject:[NSDictionary dictionaryWithObjectsAndKeys:DISH_TEXT,TITLE,content,CONTENT,did,@"id", nil]];
    }
    
    [detail addObject:[NSDictionary dictionaryWithObjectsAndKeys:ORDER_TIME,TITLE,orderTime,CONTENT, nil]];
    
    [detail addObject:[NSDictionary dictionaryWithObjectsAndKeys:DINNER_COUNT,TITLE,dinnerCount,CONTENT, nil]];
    
    [detail addObject:[NSDictionary dictionaryWithObjectsAndKeys:ORDER_TEL,TITLE,ordertel,CONTENT, nil]];
    
    [detail addObject:[NSDictionary dictionaryWithObjectsAndKeys:REMARK_TEXT,TITLE,remark,CONTENT, nil]];
   
    _dataSource.detailList = detail;
    
    _shopName = dname;
    _seatName = seatName;
    _seatType = seatType;
    _dinnerTime = dinnerTime;
    _orderseatType = [[dictionary objectForKey:@"typeid"] intValue];
    [_shopInfo setObject:jingdu forKey:@"jingdu"];
    [_shopInfo setObject:weidu forKey:@"weidu"];
    [_shopInfo setObject:dname forKey:@"name"];
    [_shopInfo setObject:address forKey:@"xianqu"];
    [_shopInfo setObject:@"" forKey:@"logo"];
    
    if (![S_EMPTY isEqualToString:seatName]) {
        if (_orderType == NewOrder) {
            [self createRightButton:@"邀请"];
        }
    }
    
    _tel = tel;
    _shopId = [dictionary objectForKey:@"did"];
    
    _orderStateLabel.text = state;
    _orderStateLabel.textColor = [self colorWithState:state];
    [_orderStateLabel autoWidthForSingleLine];
    
    [self reLayoutSubviews];
}

- (UIColor *)colorWithState:(NSString *)state
{
    NSString *colorStr = @"#F0F0F0";
    if ([state isEqualToString:@"未确认"]) {
        colorStr = @"#D9D9D9";
    }
    
    if ([state isEqualToString:@"已确认"] || [state isEqualToString:@"已到店就餐"]) {
        colorStr = @"#FFA54F";
    }
    
    UIColor *color = [UIColor colorWithHexString:colorStr];
    return color;
}

- (void)reLayoutSubviews
{
    [_headTable reloadData];
    [_detailTable reloadData];
    
    [UIView drawBorders:@[_statusView, _headTable, _detailTable]];
    [UIView autoHeightsNoMargin:@[_headTable, _detailTable]];
    [UIView autoLayoutVertical:@[_statusView, _headTable, _detailTable, _cancelOrderBtn]];
    
    _theScrollview.hidden = NO;
    [_theScrollview autoHeight];
    
    _theScrollview.height = ScreenHeight == iPhone4_Height ? iPhone4_ViewHeight : iPhone5_ViewHeight;
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

#define ORDER_INFO_TAG 1001
#define CANCEL_ORDER_TAG 1002
#define CellId @"OrderDetailCell"

@implementation OrderDetailDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
        self.headList = [[NSMutableArray alloc] initWithCapacity:3];
        self.detailList = [[NSMutableArray alloc] initWithCapacity:10];
        self.detailCell = [_viewController createCellWithNib:CellId];
    }
    return self;
}

- (void)fetchOrderInfo
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_ORDER_INFO,_viewController.orderId];
    [self get:url tag:ORDER_INFO_TAG];
}

- (void)cancelOrder
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_CANCEL_ORDER,_viewController.orderId];
    [self get:url tag:CANCEL_ORDER_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    [self processRequest:data forTag:request.tag];
    [SVProgressHUD dismiss];
}

- (void)processRequest:(NSDictionary *)data forTag:(int)tag
{
    if (tag == CANCEL_ORDER_TAG) {
        int state = [[data objectForKey:@"state"] integerValue];
        if (state == 1) {
            [SVProgressHUD showSuccessWithStatus:@"取消订单成功" duration:2];
            [_viewController pushOrPopViewController:[MyOrderViewController class]];
        }
        if (state == 2) {
            [SVProgressHUD showSuccessWithStatus:@"不存在该订单" duration:2];
        }
    }
    
    if (tag == ORDER_INFO_TAG) {
        self.orderInfoDic = [NSMutableDictionary dictionaryWithDictionary:data];
        [self.viewController setFormValues:self.orderInfoDic];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *row = nil;
    
    if (tableView.tag == 1001) {
        row = _headList[indexPath.row];
    }
    
    if (tableView.tag == 1002) {
        row = _detailList[indexPath.row];
    }
    
    return [_detailCell setContent:row];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableView.tag == 1001 ? _headList.count : _detailList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderDetailCell *cell = [_viewController createCellWithNib:CellId tableview:tableView];
    
    if (tableView.tag == 1001) {
        NSMutableDictionary *dic = [_headList objectAtIndex:indexPath.row];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [cell setContent:dic];
    }
    
    if (tableView.tag == 1002) {
        NSMutableDictionary *dic = [_detailList objectAtIndex:indexPath.row];
        [cell setContent:dic];
        
        NSString *title = [dic objectForKey:TITLE];
        if ([title isEqualToString:SEAT_TEXT] || [title isEqualToString:DISH_TEXT]) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
        if ([title isEqualToString:DINNER_TIME]) {
            cell.contentLabel.textColor = [UIColor blackColor];
            cell.contentLabel.font = [UIFont boldSystemFontOfSize:15];
        }
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 1001) {
        NSDictionary *row = [_headList objectAtIndex:indexPath.row];
        [_viewController rowSelect:row];
    }
    if (tableView.tag == 1002) {
        NSDictionary *row = [_detailList objectAtIndex:indexPath.row];
        [_viewController rowSelect:row];
    }
    
}

@end
